<template>
	<div>
		<xn-form-container
			:title="formData.id ? '编辑' : '新增'"
			:width="1000"
			:visible="visible"
			:destroy-on-close="true"
			@close="onClose"
		>
			<a-form
				:wrapper-col="{ span: 16 }"
				:label-col="{ span: 8 }"
				autocomplete="off"
				labelAlign="right"
				ref="formRef"
				:model="formData"
				:rules="formRules"
			>
				<a-row>
					<a-col :span="12">
						<a-form-item label="采购订单" name="purchaseOrderId">
							<xn-page-selector
								ref="purchaseOrderRef"
								@change="purchaseOrderChange"
								:field-names="{ label: 'proName', value: 'id' }"
								:page-function="(param) => purchasingOrderApi.getPage(param)"
								v-model:value="formData.purchaseOrderId"
								placeholder="请选择采购订单"
							>
							</xn-page-selector>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="采购方式">
							<a-input disabled v-model:value="formData.orderMethod" />
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="12">
						<a-form-item label="供应商">
							<a-input disabled v-model:value="formData.supplierName" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="采购订单号">
							<a-input disabled v-model:value="formData.code" />
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="12">
						<a-form-item label="实际到货日期" name="actualDate">
							<a-date-picker
								:getCalendarContainer="(trigger) => trigger.parentNode"
								format="YYYY-MM-DD"
								style="width: 100%"
								v-model:value="formData.actualDate"
							/>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="付款日期">
							<a-date-picker
								:getCalendarContainer="(trigger) => trigger.parentNode"
								disabled
								format="YYYY-MM-DD"
								style="width: 100%"
								v-model:value="formData.settingTime"
							/>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="12">
						<a-form-item label="采购员">
							<a-input disabled v-model:value="formData.orderPerson" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="仓库名称">
							<a-input disabled v-model:value="formData.supplierName" />
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="12">
						<a-form-item label="备注" name="remark">
							<a-input v-model:value="formData.remark" placeholder="请输入备注" allow-clear />
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="24">
						<a-row>
							<a-button type="primary" class="childAddButton" @click="addProduct()">
								<PlusOutlined />
								新增
							</a-button>
							<a-popconfirm title="是否删除?" @confirm="removeGoods()">
								<a-button style="margin-left: 12px" type="remove" danger>
									<LineOutlined />
									删除
								</a-button>
							</a-popconfirm>
						</a-row>
						<a-table
							:row-selection="options.rowSelection"
							:pagination="false"
							:columns="goodsColumns"
							:data-source="formData.purchaseSheetDetailList"
							:scroll="{ x: 1000 }"
						>
							<template #bodyCell="{ index, record, column }">
								<template v-if="column.dataIndex === 'index'">
									<span>{{ index + 1 }}</span>
								</template>

								<template v-if="column.dataIndex === 'takeDeliveryNum'">
									<a-input
										@input="takeDeliveryNumChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.takeDeliveryNum"
									/>
								</template>
								<template v-if="column.dataIndex === 'remark'">
									<a-input :style="{ width: column.width }" v-model:value="record.remark" />
								</template>
							</template>
						</a-table>
					</a-col>
				</a-row>

				<div style="margin-top: 15px">
					<span style="color: #333; font-size: 16px; font-weight: 600">合计</span>
				</div>
				<a-row :gutter="24" style="margin-bottom: 50px; margin-top: 15px; margin-left: 20px">
					<a-col :span="6">
						<div style="margin-right: 12px; display: inline-block">
							<span>采购数量:</span>
						</div>
						<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="waresNum" />
					</a-col>
					<a-col :span="6">
						<div style="margin-right: 12px; display: inline-block">
							<span>含税总金额</span>
						</div>
						<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="taxAmount" />
					</a-col>
					<a-col :span="6">
						<div style="margin-right: 12px; display: inline-block">
							<span>不含税总金额</span>
						</div>
						<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="noTaxAmount" />
					</a-col>
				</a-row>
			</a-form>

			<template #footer>
				<a-button type="primary" @click="onSubmit" :loading="submitLoading">提交</a-button>
			</template>
		</xn-form-container>

		<productSelector
			:data-provider="getOrderDetailList"
			:columns="selectorColumns"
			@onProductChange="onProductChange"
			ref="productsRef"
		/>
	</div>
</template>

<script setup name="purchasingReceiptForm">
	import { required } from '@/utils/formRules'
	import { message } from 'ant-design-vue'
	import { nextTick, toRaw } from 'vue'
	import dayjs from 'dayjs'
	import productSelector from '@/components/Selector/productSelector.vue'
	import purchasingOrderApi from '@/api/purchasing/order/purchasingOrderApi'
	import xnPageSelector from '@/components/XnPageSelect/index.vue'
	import purchasingReceiptApi from '@/api/purchasing/receipt/purchasingReceiptApi'
	import purchasingOrderDetailApi from '@/api/purchasing/order/purchasingOrderDetailApi'

	// 定义emit事件
	//PROCUREMENT_PARTNERS
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	const visible = ref(false)
	const formRef = ref()
	const purchaseOrderRef = ref()
	const productsRef = ref()

	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	const submitLoading = ref(false)
	const waresNum = ref(0)
	const taxAmount = ref(0)
	const noTaxAmount = ref(0)

	const purchaseOrderChange = (id) => {
		purchasingOrderApi
			.detail({
				id: id
			})
			.then((res) => {
				let origin = formData.value
				let detailList = res.purchaseOrderDetailList.map((it) => {
					if (!it['receiveNum']) {
						it['receiveNum'] = it['orderNum']
					}
					it['remark'] = ''
					it['code'] = it['proMaterial'].code
					it['name'] = it['proMaterial'].name
					it['unit'] = it['proMaterial'].unit
					it['spec'] = it['proMaterial'].spec
					it['key'] = it['materialId']
					return it
				})
				let formValue = {
					proName: res.proName,
					proId: res.proId,
					orderMethod: res.orderMethod,
					orderPerson: res.orderPerson,
					orderPersonId: res.orderPersonId,
					supplierId: res.supplierId,
					supplierName: res.supplierName,
					warehouseName: res.warehouseName,
					warehouseId: res.warehouseId,
					code: res.code,
					settingTime: dayjs(res.settingTime),
					purchaseSheetDetailList: detailList
				}
				formData.value = Object.assign(origin, formValue)
				waresNum.value = totalOrderNum()
				taxAmount.value = totalTax()
				noTaxAmount.value = totalExcludingTaxTax()
			})
	}

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		formData.value = {}
		if (record) {
			let params = { ...record }
			formData.value.id = params.id
			formData.value.purchaseOrderId = params.purchaseOrderId
			formData.value.remark = params.remark
			formData.value.actualDate = ref(dayjs(params.actualDate))
			purchaseOrderChange(params.purchaseOrderId)
		} else {
			formData.value.actualDate = ref(dayjs())
		}

		nextTick(() => {
			purchaseOrderRef.value.onPage({})
		})
	}

	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}

	const addProduct = () => {
		if (!formData.value.purchaseOrderId) {
			message.error('请选择采购订单')
			return
		}
		if (!formData.value.purchaseSheetDetailList) {
			formData.value.purchaseSheetDetailList = []
		}
		productsRef.value.showDialog(formData.value.purchaseSheetDetailList)
	}
	const removeGoods = () => {
		let datas = formData.value.purchaseSheetDetailList
		selectedRowKeys.value.forEach((element) => {
			let index = datas.findIndex((it) => {
				return it['id'] == element
			})
			if (index >= 0) {
				datas.splice(index, 1)
			}
		})
		selectedRowKeys.value = []
		waresNum.value = totalOrderNum()
		taxAmount.value = totalTax()
		noTaxAmount.value = totalExcludingTaxTax()
	}
	const selectedRowKeys = ref([])

	const takeDeliveryNumChange = (record) => {
		let value = parseInt(record.takeDeliveryNum.replace(/[^\d]+/g, ''))
		if (isNaN(value)) {
			record.takeDeliveryNum = ''
			record.receiveNum = '0'
		} else {
			let orderNum = parseInt(record.orderNum)
			if (value > orderNum) {
				record.takeDeliveryNum = record.orderNum
				record.receiveNum = '0'
			} else {
				record.takeDeliveryNum = value
				record.receiveNum = orderNum - value
			}
		}
	}

	const totalExcludingTaxTax = () => {
		let orderList = formData.value.purchaseSheetDetailList || []
		let amount = 0
		orderList.forEach((it) => {
			let noTaxPrice = it['noTaxPrice']
			if (noTaxPrice) {
				amount += parseFloat(noTaxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}
	const totalTax = () => {
		let orderList = formData.value.purchaseSheetDetailList || []
		let amount = 0
		orderList.forEach((it) => {
			let taxPrice = it['taxPrice']
			if (taxPrice) {
				amount += parseFloat(taxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}

	const totalOrderNum = () => {
		let orderList = formData.value.purchaseSheetDetailList || []
		let amount = 0
		orderList.forEach((it) => {
			let orderNum = it['orderNum']
			if (orderNum) {
				amount += parseInt(orderNum)
			}
		})
		return amount
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}

	// 默认要校验的
	const formRules = {
		purchaseOrderId: [required('请选择采购订单')],
		actualDate: [required('请选择实际到货日期')]
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				let orderList = toRaw(formData.value.purchaseSheetDetailList) || []
				if (orderList.length <= 0) {
					message.error('请添加商品')
					return
				}
				let msg = null
				let itemRules = [
					{
						field: 'takeDeliveryNum',
						error: '收货数量不能为空!'
					}
				]
				for (let i = 0; i < orderList.length; i++) {
					for (let rule of itemRules) {
						let item = orderList[i]
						let itemValue = item[rule['field']]
						if (!itemValue) {
							msg = `第${i + 1}行${rule['error']}`
							break
						}
					}
				}
				if (msg) {
					message.error(msg)
					return
				}
				submitLoading.value = true
				let params = { ...formData.value }
				if (params.id) {
					params.purchaseSheetDetailEditParamList = orderList
				} else {
					params.purchaseSheetDetailList = orderList
				}
				purchasingReceiptApi
					.addOrEdit(
						Object.assign(params, {
							actualDate: params.actualDate.format('YYYY-MM-DD HH:mm:ss'),
							noTaxAmount: noTaxAmount.value,
							taxAmount: taxAmount.value,
							waresNum: waresNum.value
						})
					)
					.then(() => {
						visible.value = false
						emit('successful')
					})
					.catch(() => {})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})

	const onProductChange = (items) => {
		let purchaseSheetDetailList = formData.value.purchaseSheetDetailList || []
		items.forEach((it) => {
			it['key'] = undefined
			if (!it['deliveryDate']) {
				it['deliveryDate'] = ref(dayjs())
			}
			let find = purchaseSheetDetailList.find((item) => {
				return item['materialId'] == it['materialId']
			})

			if (find) {
				it = Object.assign(it, find)
			}
		})
		formData.value.purchaseSheetDetailList = items
		waresNum.value = totalOrderNum()
	}

	const getOrderDetailList = (parameter) => {
		console.log("getOrderDetailList",parameter)
		return purchasingOrderDetailApi
			.getPage(
				Object.assign(parameter, {
					orderId: formData.value.purchaseOrderId
				})
			)
			.then((res) => {
				res.records.forEach((it) => {
					it['key'] = it['id']
					it['materialId'] = it['id']
					it['remark'] = ''
				})
				return res
			})
			.catch(() => {})
	}

	const selectorColumns = [
		{
			title: '序号',
			dataIndex: 'index',
			ellipsis: true,
			width: 80,
			align: 'center'
		},
		{
			title: '商品编号',
			width: 100,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true
		},
		{
			title: '商品名称',
			width: 120,
			dataIndex: 'name',
			align: 'center',
			ellipsis: true
		},
		{
			title: '品牌',
			width: 100,
			dataIndex: 'brand',
			align: 'center',
			ellipsis: true
		},
		{
			title: '规格',
			width: 100,
			dataIndex: 'spec',
			align: 'center',
			ellipsis: true
		},
		{
			title: '商品单价',
			width: 100,
			dataIndex: 'unitPrice',
			align: 'center',
			ellipsis: true
		}
	]

	const goodsColumns = [
		{
			title: '序号',
			width: 80,
			dataIndex: 'index',
			align: 'center'
		},
		{
			title: '商品编号',
			width: 120,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true
		},
		{
			title: '商品名称',
			dataIndex: 'name',
			width: 180,
			align: 'center',
			ellipsis: true
		},
		{
			title: '单位',
			dataIndex: 'unit',
			width: 100,
			align: 'center'
		},
		{
			title: '规格型号',
			dataIndex: 'spec',
			width: 120,
			align: 'center'
		},
		{
			title: '采购价格',
			dataIndex: 'price',
			width: 120,
			align: 'center'
		},
		// {
		// 	title: '税率',
		// 	dataIndex: 'taxRate',
		// 	width: 120,
		// 	align: 'center'
		// },

		{
			title: '采购数量',
			dataIndex: 'orderNum',
			width: 120,
			align: 'center'
		},
		{
			title: '剩余收货数量',
			dataIndex: 'receiveNum',
			width: 120,
			align: 'center'
		},
		{
			title: '收货数量',
			dataIndex: 'takeDeliveryNum',
			width: 120,
			align: 'center'
		},
		// {
		// 	title: '含税金额',
		// 	dataIndex: 'taxPrice',
		// 	width: 120,
		// 	align: 'center'
		// },
		// {
		// 	title: '不含税金额',
		// 	dataIndex: 'noTaxPrice',
		// 	width: 140,
		// 	align: 'center'
		// },
		{
			title: '备注',
			dataIndex: 'remark',
			width: 200,
			align: 'center'
		}
	]
</script>

<style scoped :type="less">
	.childAddButton {
		margin-bottom: 10px;
	}
</style>
